package qeug.shsh.opplugin;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.ClientProperties;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.org.OrgUnitServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

public class DailyapplybilPlugin extends AbstractFormPlugin  {

    /**
     * 事前申请单表单插件
     **/
    private static String SUBMIT = "bar_submit";//提交按钮
    private static String UNSUBMIT = "bar_unsubmitp";//撤销按钮
    private static String SAVE = "bar_save";//保存按钮

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String fieldKey = e.getProperty().getName();
        //申请金额、宾客人数、陪客人数、接待标准、申请数量
        if ("expenseamount".equals(fieldKey) || "qeug_guest".equals(fieldKey) || "qeug_accompany".equals(fieldKey) || "qeug_reception_standards".equals(fieldKey) || "qeug_application".equals(fieldKey)) {
            if (isBT2()) {
                DynamicObjectCollection expenseCollection = this.getModel().getEntryEntity("expenseentryentity");//费用明细分录
                BigDecimal applyAmountTotal = BigDecimal.ZERO;//申请金额总金额
                BigDecimal guest = (BigDecimal) getModel().getValue("qeug_guest");//宾客人数
                BigDecimal accompany = (BigDecimal) getModel().getValue("qeug_accompany");//陪客人数
                if (guest.compareTo(BigDecimal.ZERO) != 0 || accompany.compareTo(BigDecimal.ZERO) != 0) {
                    for (DynamicObject expenseEntry : expenseCollection) {
                        BigDecimal applyAmount = expenseEntry.getBigDecimal("expenseamount");//申请金额
                        applyAmountTotal = applyAmountTotal.add(applyAmount);
                    }
                    String value = (String) getModel().getValue("qeug_reception_standards");//接待标准下拉值
                    if ("0".equals(value) || "1".equals(value)) {
                        if (accompany.compareTo(guest) > 0) {
                            this.getView().showErrorNotification("接待标准为一级及以上陪客人数不能超过宾客人数!");
                        }
                    } else if ("2".equals(value) || "3".equals(value)) {
                        BigDecimal halfGuestAmount = guest.divide(new BigDecimal(2), 0, RoundingMode.HALF_UP);
                        if (accompany.compareTo(halfGuestAmount) > 0) {
                            this.getView().showErrorNotification("接待标准为二级及以下陪客人数不能超过宾客人数的一半!");
                        }
                    }
                    if (applyAmountTotal.compareTo(BigDecimal.ZERO) != 0) {
                        BigDecimal aggregate = guest.add(accompany);//总人数
                        BigDecimal average = applyAmountTotal.divide(aggregate, 2, RoundingMode.HALF_UP);//平均消费
                        getModel().setValue("qeug_per_capita_amount", average);
                    }
                }
                String value = (String) getModel().getValue("qeug_reception_standards");//接待标准下拉值
                if ("0".equals(value)) {
                    DynamicObject supplies = (DynamicObject) this.getModel().getValue("qeug_supplies");//物料
                    BigDecimal application = (BigDecimal) getModel().getValue("qeug_application");//申请数量
                    if (supplies != null) {
                        QFilter[] qFilter = new QFilter[]{
                                new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id"))};
                        DynamicObject expense = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_special", qFilter);
                        int specialValue = expense.getInt("qeug_special");//特殊接待标准
                        if (application.compareTo(BigDecimal.valueOf(specialValue)) > 0) {
                            this.getView().showErrorNotification("申请数量不能超过特殊接待标准数量!");
                        }
                    }
                } else if ("1".equals(value)) {
                    DynamicObject supplies = (DynamicObject) this.getModel().getValue("qeug_supplies");//物料
                    BigDecimal application = (BigDecimal) getModel().getValue("qeug_application");//申请数量
                    if (supplies != null) {
                        QFilter[] qFilter = new QFilter[]{
                                new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id"))};
                        DynamicObject expense = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_first_order", qFilter);
                        int first_order = expense.getInt("qeug_first_order");//一级接待标准
                        if (application.compareTo(BigDecimal.valueOf(first_order)) > 0) {
                            this.getView().showErrorNotification("申请数量不能超过一级接待标准数量!");
                        }
                    }
                } else if ("2".equals(value)) {
                    DynamicObject supplies = (DynamicObject) this.getModel().getValue("qeug_supplies");//物料
                    BigDecimal application = (BigDecimal) getModel().getValue("qeug_application");//申请数量
                    if (supplies != null) {
                        QFilter[] qFilter = new QFilter[]{
                                new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id"))};
                        DynamicObject expense = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_second_level", qFilter);
                        int second_level = expense.getInt("qeug_second_level");//二级接待标准
                        if (application.compareTo(BigDecimal.valueOf(second_level)) > 0) {
                            this.getView().showErrorNotification("申请数量不能超过二级接待标准数量!");
                        }
                    }
                } else if ("3".equals(value)) {
                    DynamicObject supplies = (DynamicObject) this.getModel().getValue("qeug_supplies");//物料
                    BigDecimal application = (BigDecimal) getModel().getValue("qeug_application");//申请数量
                    if (supplies != null) {
                        QFilter[] qFilter = new QFilter[]{
                                new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id"))};
                        DynamicObject expense = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_three_level", qFilter);
                        int three_level = expense.getInt("qeug_three_level");//三级接待标准
                        if (application.compareTo(BigDecimal.valueOf(three_level)) > 0) {
                            this.getView().showErrorNotification("申请数量不能超过三级接待标准数量!");
                        }
                    }
                }
            }
        }  else if ("qeug_supplies".equals(fieldKey)) {
            DynamicObject supplies = (DynamicObject) this.getModel().getValue("qeug_supplies");//物料
            loadExpenseItemAndInventoryQuantity(supplies);
        }
    }

    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        super.beforePropertyChanged(e);
        String fieldKey = e.getProperty().getName();
        if ("qeug_supplies".equals(fieldKey)) {
            DynamicObject supplies = (DynamicObject) getModel().getValue("qeug_supplies");
            loadExpenseItemAndInventoryQuantity(supplies);
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addItemClickListeners("tbmain");//监听按钮
    }


    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
        super.beforeItemClick(evt);
        String itemKey = evt.getItemKey();
        if (isBT2()) {
            if (itemKey.equals(SUBMIT)) {
                //提交按钮
                DynamicObjectCollection expenseCollection = getModel().getEntryEntity("expenseentryentity");
                int haveSuppliers = 0; // 有供应商的行数
                int correctQuantity = 0; // 提交正确的行数
                int repetition = 0;//重复行数
                List<DynamicObject> orderList = new ArrayList<>(); // 定义一个列表用于存储多条数据
                List<String> suppliesNumbers = new ArrayList<>();
                for (DynamicObject expense : expenseCollection) {
                    BigDecimal application = expense.getBigDecimal("qeug_application");//申请数量
                    DynamicObject supplies = expense.getDynamicObject("qeug_supplies");//物料
                    if (supplies != null) {
                        haveSuppliers++;
                        String suppliesNumber = supplies.getString("number");
                        for (int i = 0; i < suppliesNumbers.size(); i++) {
                            if (suppliesNumber.equals(suppliesNumbers.get(i))) {
                                repetition++;
                            }
                        }
                        QFilter[] qFilter = new QFilter[]{
                                new QFilter("qeug_supplies.number", QCP.equals, supplies.get("number"))};
                        DynamicObject inventory = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_inventory_quantit,qeug_total_quantity,qeug_quantity_used", qFilter);
                        BigDecimal inventory_quantity = inventory.getBigDecimal("qeug_inventory_quantit");//库存数量
                        BigDecimal total_quantity = inventory.getBigDecimal("qeug_total_quantity");//总数量
                        BigDecimal quantity = inventory_quantity.subtract(application);//剩余库存数量
                        BigDecimal subtract = total_quantity.subtract(quantity);//已用数量
                        //剩余库存数量减去申请数量大于0，则更新库存数量和已用数量
                        if (inventory_quantity.compareTo(application) >= 0) {
                            inventory.set("qeug_inventory_quantit", quantity);
                            inventory.set("qeug_quantity_used", subtract);
                            orderList.add(inventory); // 将 inventory 对象添加到列表中
                            correctQuantity++;
                        }
                        suppliesNumbers.add(suppliesNumber);
                    }
                }
                if (repetition <= 0) {
                    if (haveSuppliers == correctQuantity) {
                        DynamicObject[] order = orderList.toArray(new DynamicObject[0]); // 将列表转换为数组
                        SaveServiceHelper.save(order); // 保存全部数据
                    }else{
                        evt.setCancel(true); // 取消原来的操作
                        this.getView().showErrorNotification("选中的单据中存在申请数量超过剩余库存数量！请刷新费用明细");
                    }
                } else {
                    evt.setCancel(true); // 取消原来的操作
                    this.getView().showErrorNotification("冲突！费用明细中存在相同的物料");
                }

            } else if (itemKey.equals(UNSUBMIT)) {
                //撤销按钮
                DynamicObjectCollection expenseCollection = getModel().getEntryEntity("expenseentryentity");
                for (DynamicObject expense : expenseCollection) {
                    BigDecimal application = expense.getBigDecimal("qeug_application");//申请数量
                    DynamicObject supplies = expense.getDynamicObject("qeug_supplies");//物料
                    if (supplies != null) {
                        QFilter[] qFilter = new QFilter[]{
                                new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id"))};
                        DynamicObject inventory = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_inventory_quantit,qeug_total_quantity,qeug_quantity_used", qFilter);
                        BigDecimal inventory_quantity = inventory.getBigDecimal("qeug_inventory_quantit");//库存数量
                        BigDecimal total_quantity = inventory.getBigDecimal("qeug_total_quantity");//总数量
                        BigDecimal quantity = inventory_quantity.add(application);//剩余库存数量
                        BigDecimal subtract = total_quantity.subtract(quantity);//已用数量
                        inventory.set("qeug_inventory_quantit", quantity);
                        inventory.set("qeug_quantity_used", subtract);
                        DynamicObject[] order = new DynamicObject[]{inventory};
                        SaveServiceHelper.save(order);
                    }
                }
            } else if (itemKey.equals(SAVE)) {
                //保存按钮
                DynamicObjectCollection expenseCollection = getModel().getEntryEntity("expenseentryentity");
                int repetition = 0;//重复行数
                List<String> suppliesNumbers = new ArrayList<>();
                for (DynamicObject expense : expenseCollection) {
                    DynamicObject supplies = expense.getDynamicObject("qeug_supplies");//物料
                    if (supplies != null) {
                        String suppliesNumber = supplies.getString("number");
                        for (String i : suppliesNumbers) {
                            if (suppliesNumber.equals(i)) {
                                repetition++;
                            }
                        }
                        suppliesNumbers.add(suppliesNumber);
                    }
                }
                if (repetition > 0) {
                    evt.setCancel(true); // 取消原来的操作
                    this.getView().showErrorNotification("冲突！费用明细中存在相同的物料");
                }
            }
        }
    }

    public boolean isBT2() {
        DynamicObject billType_data = (DynamicObject) getModel().getValue("qeug_document_type");//单据类型
        String billTypeNumber = billType_data.getString("number");
        return "er_dailyapplybill_BT2".equals(billTypeNumber);//单据类型为接待申请
    }

    public void loadExpenseItemAndInventoryQuantity(DynamicObject supplies) {
        if (supplies != null) {
            QFilter[] qFilters = new QFilter[]{
                    new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id")).and("qeug_isenable", QCP.equals, true)
            };
            QFilter[] qFilter = new QFilter[]{
                    new QFilter("qeug_supplies.id", QCP.equals, supplies.get("id"))
            };
            DynamicObject inventory = BusinessDataServiceHelper.loadSingle("qeug_tobacco_inventory", "qeug_inventory_quantit", qFilter);
            DynamicObject expense = BusinessDataServiceHelper.loadSingle("qeug_supplies_expense", "qeug_expense.*", qFilters);
            if (expense != null) {
                getModel().setValue("expenseitem", expense.getDynamicObject("qeug_expense"));
            } else {
                getModel().setValue("qeug_supplies", null);
                getModel().setValue("expenseitem", null);
                getModel().setValue("qeug_inventory_quantity", null);
                getView().showErrorNotification("该物料未关联费用名目！");
            }
            if (inventory != null) {
                String quantit = inventory.getString("qeug_inventory_quantit");
                if (Integer.parseInt(quantit) > 0) {
                    getModel().setValue("qeug_inventory_quantity", quantit);
                } else {
                    getModel().setValue("qeug_supplies", null);
                    getModel().setValue("expenseitem", null);
                    getModel().setValue("qeug_inventory_quantity", null);
                    getView().showErrorNotification("该物料库存不足！");
                }
            } else {
                getModel().setValue("qeug_supplies", null);
                getModel().setValue("expenseitem", null);
                getModel().setValue("qeug_inventory_quantity", null);
                getView().showErrorNotification("该物料未关联库存！");
            }
        }
    }
}
